import 'dart:io';
import 'dart:async';
// import 'package:pedantic/pedantic.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import '../../common/widgets.dart';

class HttpMonitorPage extends StatefulWidget {
  @override
  _HttpMonitorPageState createState() => _HttpMonitorPageState();
}

class _HttpMonitorPageState extends State<HttpMonitorPage> {
  @override
  void initState() {
    startServer();
    super.initState();
  }

  @override
  void dispose() {
    stopServer();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    HttpClient client = new HttpClient();

    return Scaffold(
      appBar: AppBar(
        title: Text('网络监控测试页面'),
      ),
      body: Center(
        child: ListView(
          padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 8.0, bottom: 8.0),
          children: [
            buildButton(
              context,
              "404",
              () {
                client.getUrl(serverUrl.resolve('/404_error')).then((HttpClientRequest request) {
                  return request.close();
                }).then((HttpClientResponse response) {
                  print('statusCode: ${response.statusCode}');
                });
              },
            ),
            buildButton(
              context,
              "500",
              () {
                client.getUrl(serverUrl.resolve('/500_error')).then((HttpClientRequest request) {
                  return request.close();
                }).then((HttpClientResponse response) {
                  print('isRedirect：${response.isRedirect}');
                  response.redirects.forEach((element) {
                    print('redirect url: ${element.location.toString()}');
                    print('redirect statusCode: ${element.statusCode}');
                    print('redirect method: ${element.method}');
                  });
                  print('statusCode: ${response.statusCode}');
                });
              },
            ),
            buildButton(
              context,
              "connect timeout\n(http://aaa.com/)",
              () {
                HttpClient timeoutClient = new HttpClient();
                timeoutClient.connectionTimeout = Duration(milliseconds: 10);
                timeoutClient.getUrl(Uri.parse('http://aaa.com/')).then((HttpClientRequest request) {
                  return request.close();
                }).then((HttpClientResponse response) {
                  print('statusCode: ${response.statusCode}');
                });
              },
            ),
            buildButton(
              context,
              "SSL Error1",
              () {
                client
                    .openUrl(
                        'test', Uri.parse("https://apm.rangers.com.cn/apminsightdemo/app/network/http/err/distribute"))
                    .then((HttpClientRequest request) {
                  return request.close();
                }).then((HttpClientResponse response) {
                  print('statusCode: ${response.statusCode}');
                });
              },
            ),
            buildButton(
              context,
              "SSL Error2\n(与SSL Error1相同域名、不同链接，会产生相同的传输层错误，在平台上会被聚合到一起：https://apm.rangers.com.cn/*)",
              () {
                client
                    .getUrl(Uri.parse(
                        "https://apm.rangers.com.cn/apminsightdemo/app/network/http/summary?uuid=6cf6c615-9a74-dd6f-d3d6-cb6eec69f476"))
                    .then((HttpClientRequest request) {
                  return request.close();
                }).then((HttpClientResponse response) {
                  print('statusCode: ${response.statusCode}');
                });
              },
            ),
            buildButton(
              context,
              "IO Error",
              () {
                client
                    .getUrl(Uri.parse("https://api.huangzewei.me/v1/review/mask/info?app=2&ver=9.3.5&"
                        "mod=V1818A&version_code=695&chn=mjnuu_vivo&source=2&sys=android_8.1.0&token=ea6685900"
                        "7556cff928abeb825e91bc3&sig=47a8b56af608a027b150ef3490f47dbe&build=695&review=1&bundl"
                        "e_id=com.nuu.video&lan=0&source_id=375999679919317766&sdk=9.3.5&net=0&did=51D29B7F29B"
                        "74BD1C761E5784BCC9EA0&ts=1625229217726"))
                    .then((HttpClientRequest request) {
                  return request.close();
                }).then((HttpClientResponse response) {
                  print('statusCode: ${response.statusCode}');
                });
              },
            ),
            buildButton(
              context,
              "成功的请求",
              () {
                var uri = Uri.parse("https://www.baidu.com/");
                client.getUrl(uri).then((HttpClientRequest request) {
                  return request.close();
                }).then((HttpClientResponse response) {
                  print('statusCode: ${response.statusCode}');
                });
              },
            ),
            buildButton(
              context,
              "重定向的成功请求",
              () {
                client.getUrl(serverUrl.resolve('/redirect')).then((HttpClientRequest request) {
                  return request.close();
                }).then((HttpClientResponse response) {
                  print('isRedirect：${response.isRedirect}');
                  response.redirects.forEach((element) {
                    print('redirect url: ${element.location.toString()}');
                    print('redirect statusCode: ${element.statusCode}');
                    print('redirect method: ${element.method}');
                  });
                  print('statusCode: ${response.statusCode}');
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}

/// The current server instance.
HttpServer? _server;

/// The URL for the current server instance.
Uri get serverUrl => Uri.parse('http://localhost:${_server!.port}');

/// Starts a new HTTP server.
Future<void> startServer() async {
  _server = (await HttpServer.bind('localhost', 0))
    ..listen((request) async {
      var path = request.uri.path;
      var response = request.response;

      if (path == '/404_error') {
        response
          ..statusCode = 404
          ..contentLength = 0;
        unawaited(response.close());
        return;
      }

      if (path == '/500_error') {
        response
          ..statusCode = 500
          ..contentLength = 0;
        unawaited(response.close());
        return;
      }

      if (path == '/redirect') {
        response
          ..statusCode = 302
          ..headers.set('location', 'https://www.baidu.com/')
          ..contentLength = 0;
        unawaited(response.close());
        return;
      }
    });
}

/// Stops the current HTTP server.
void stopServer() {
  if (_server != null) {
    _server!.close();
    _server = null;
  }
}
